/**
 * 
 */
package edu.hadassah.prettyprint.xmlp;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

import edu.hadassah.prettyprint.config.ApplicationContextFactory;
import edu.hadassah.prettyprint.config.IApplicationContext;
import edu.hadassah.prettyprint.doc.Document;
import edu.hadassah.prettyprint.parser.Parser;
import edu.hadassah.prettyprint.parser.ParserException;
import edu.hadassah.prettyprint.printer.IDocumentPrinterVisitor;


/**
 * @author persikov
 * 
 */
public class XmlPrinterApp {

	private final IApplicationContext applicationContext;

	/**
	 * @param xmlpConfig
	 */
	public XmlPrinterApp(IApplicationContext context) {
		this.applicationContext = context;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		try {
			IApplicationContext context = ApplicationContextFactory.createContextFromCmdArguments(args);
			if (context != null) {
				new XmlPrinterApp(context).run();
			}
		} catch (ParserException e) {
			logError(e);
		} catch (IOException e) {
			logError(e);
			printUsage();
		}
	}

	/**
	 * @param e
	 */
	private static void logError(Exception e) {
		System.err.println(e.getMessage());
	}

	/**
	 * @throws ParserException 
	 * @throws IOException 
	 * @throws IOException 
	 * 
	 */
	private void run() throws ParserException, IOException {
		Document document = readDocument();
		writeDocument(document);
	}

	/**
	 * @param document
	 * @throws IOException
	 */
	private void writeDocument(Document document) throws IOException {
		IDocumentPrinterVisitor printer = applicationContext.getDocumentPrinter();
		Writer writer = applicationContext.getDocumentWriter();
		document.accept(printer);
		String output = printer.getResultString();
		try {
			writer.write(output);
		} finally {
			writer.close();
		}
	}

	/**
	 * @return
	 * @throws FileNotFoundException
	 * @throws ParserException
	 * @throws IOException
	 */
	private Document readDocument() throws ParserException, IOException {
		Document document;
		Reader in = applicationContext.getDocumentReader(); 
		try {
			Parser parser = applicationContext.getDocumentParser();
			document = parser.parse(in);
			return document;
		} finally {
			in.close();
		}
	}


	private static void printUsage() {
		System.err.println("The syntax of the command is:\nxmlp [-nc] [-na] xmlFileName" +
				"\n\t-nc\tXML attributes not appears in the output." +
		"\n\t-na\tcomments not appears in the output.");
	}

}
